//
//  LssOAuthViewController.swift
//  freeChatting
//
//  Created by mac on 16/4/18.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
/*
App Key：1670546686
App Secret：dd79ba0a7d98a1564f2760c3405b792e
授权回调页：http://www.baidu.com/
*/
class LssOAuthViewController: UIViewController {
//    override func loadView() {
//        view = loginWebView
//        loginWebView.delegate = self
//        //创建urlString
//        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
//        let url = NSURL(string: urlString)
//        let request = NSURLRequest(URL: url!)
//        loginWebView.loadRequest(request)
//    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view = loginWebView
        loginWebView.delegate = self
        //创建urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        loginWebView.loadRequest(request)

        setUpUI()
        setUpNavigation()
    }
    //MARK:- 设置UI
    private func setUpUI(){
        view.backgroundColor = UIColor.whiteColor()
    }
    //MARK:- 设置导航栏
    private func setUpNavigation(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoAdd")
        navigationItem.title = "微博登录"
    }
    //MARK:- 点击取消按钮返回
    @objc private func cancelAction(){
    dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK:- 点击自动填充按钮，自动填充用户名和密码
    @objc private func autoAdd(){
        let jsString = "document.getElementById('userId').value='\(userName)';document.getElementById('passwd').value='\(passWord)'"
        // JS注入
        loginWebView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    //获取code码
    
    private lazy var loginWebView: UIWebView = UIWebView()
}
//MARK:- 监测网络请求，获取code
extension LssOAuthViewController :UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(redirect_uri) {
            //截取字符串
            if let q = request.URL?.query{
            //获取code
                let code = q.substringFromIndex("code=".endIndex)
                getAccess_token(code)
               return false
            }
        }
        return true
    }
    
}
extension LssOAuthViewController{
    //MARK:- OAuth2/access token
    
    func getAccess_token(code:String){
    let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":client_id,
                      "client_secret":client_secret,
                      "grant_type": "authorization_code",
                      "code":code,
                      "redirect_uri":redirect_uri]
        CZNetworkTools.sharedTools.request(CZRequestMethod.POST, urlString: urlString, params: params) { (response, error) -> () in
            if (error != nil){
            print(error)
                return
            }
            guard let dataDict = response as? [String:AnyObject] else{
                print("返回的不是一个字典")
            return
            }
           let account = LssUserAccount(dict: dataDict)
            
            self.getUserInfo(account)
        }
    }
    
    //MARK:- 获取用户信息
   
    func getUserInfo(account:LssUserAccount){
    let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["access_token":account.access_token!,
                      "uid":account.uid!]
        CZNetworkTools.sharedTools.request(CZRequestMethod.GET, urlString: urlString, params: params) { (response, error) -> () in
            if error != nil{
            print(error)
            }
            guard let dataDict = response as? [String: AnyObject] else{
            print("返回的不是一个字典")
                return
            }
            account.screen_name = dataDict["screen_name"] as? String
            account.avatar_large = dataDict["avatar_large"] as? String
            //保存数据
            LssAppAccountTools.sharedAccountTools.saveUserAccount(account)
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName("SwitchRootViewController", object: nil)
            })
        }
    }
}